package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.commonutils.ResultCode;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.eduservice.service.client.VodClient;
import com.atguigu.servicebase.exceptionhandler.CustomizeException;
import com.mysql.cj.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 课程小节视频信息 前端控制器
 * </p>
 *
 * @author hwt
 * @since 2022-08-23
 */
@RestController
@RequestMapping("eduservice/video")
public class EduVideoController {

    @Resource
    EduVideoService service;

    // 注入远程调用接口
    @Resource
    VodClient vodClient;

    // 增删改查  TODO
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo video) {
        return service.save(video) ? R.ok() : R.error();
    }

    // TODO 删除小结时，视频需要删除，而删除视频操作，
    //  是在 service_vod 模块中，这里就可以通过微服务中的框架实现跨进程调用
    @GetMapping("deleteVideo/{videoId}")
    public R deleteVideo(@PathVariable String videoId) {

        EduVideo byId = service.getById(videoId);
        // 判断是否有视频
        if (!StringUtils.isNullOrEmpty(byId.getVideoSourceId())){
            // 有才进行远程删除
            R delete = vodClient.delete(byId.getVideoSourceId());
            // 删除失败直接抛异常终止
            if (!delete.getSuccess()) {
               throw new CustomizeException(ResultCode.ERROR.getValue(), "删除失败，请稍后重试");
            }
        }
        // 没有视频，或者删除完成了，再进行删除数据库中的小结
        return service.removeById(videoId) ? R.ok() : R.error().message("删除失败，请稍后重试");

    }

    @PostMapping("update")
    public R update(@RequestBody EduVideo video) {
        return service.updateById(video) ? R.ok() : R.error();
    }

    @GetMapping("getVideo/{ById}")
    public R getByVideoId(@PathVariable String ById) {
        return R.ok().data("video", service.getById(ById));
    }


}

